/*
 * ManageUsersFrame.java
 *
 * Created on Dec 16, 2011, 12:14:56 AM
 */
package gui;


/**
 *
 * @author suzann
 */

/*
 * Import Java Classes
 */

import db.DatabaseManager;
import db.entity.UserAccount;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;

import util.Activity;
import util.Authentication;

public class ManageUsersFrame extends javax.swing.JFrame {

    /** Creates new form ManageUsersFrame */
    public ManageUsersFrame() {
        initComponents();
        dm = new DatabaseManager();
        dlModel = new DefaultListModel();
        
        initUsers();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlUsers = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jtxUserID = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtxFullName = new javax.swing.JTextField();
        jbtDelete = new javax.swing.JButton();
//        jbtSave = new javax.swing.JButton();
//        jbtEdit = new javax.swing.JButton();
        jbtCreate = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("User ID");

        jlUsers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jlUsers.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jlUsersValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jlUsers);

        jLabel2.setText("User ID");

        jLabel3.setText("Full Name");

        jbtDelete.setText("Delete");
        jbtDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDeleteActionPerformed(evt);
            }
        });

//        jbtSave.setText("Save");
//        jbtSave.addActionListener(new java.awt.event.ActionListener() {
//            public void actionPerformed(java.awt.event.ActionEvent evt) {
 //               jbtSaveActionPerformed(evt);
//            }
//        });

//        jbtEdit.setText("Edit");
//        jbtEdit.addActionListener(new java.awt.event.ActionListener() {
//            public void actionPerformed(java.awt.event.ActionEvent evt) {
 //               jbtEditActionPerformed(evt);
//            }
//        });

        jbtCreate.setText("Create");
        jbtCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCreateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel1)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jbtCreate)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jtxUserID, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jtxFullName, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
//                        .addComponent(jbtEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
//                        .addComponent(jbtSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtDelete)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jtxUserID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jtxFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtCreate))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
//                    .addComponent(jbtEdit)
//                    .addComponent(jbtSave)
                    .addComponent(jbtDelete))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-576)/2, (screenSize.height-529)/2, 576, 529);
    }// </editor-fold>

    /**********************************************************
     * Action Listeners
     *********************************************************/
//    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
//        // TODO add your handling code here:
//    }                                      

//    private void jbtEditActionPerformed(java.awt.event.ActionEvent evt) {                                        
//    	toggleTextAndButtons(true);
//    }                                       

    private void jbtDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
    	deleteUser();
    }                                         

    private void jlUsersValueChanged(javax.swing.event.ListSelectionEvent evt) {                                     
        setTextFieldValue();
    }                                    

    private void jbtCreateActionPerformed(java.awt.event.ActionEvent evt) {
    	createUser();
    }

    /**********************************************************
     * Internal Methods
     *********************************************************/
    /**
     * This method is to initialize the user list when frame startup.
     */
    private void initUsers()
    {
    	dlModel.clear();
    	
        //get the list of users from DB
        uList = dm.listUserAccount();
        List <String> users = new ArrayList<String>();
        
        //set the JList of the users with the default model
        jlUsers.setModel(dlModel);
        
        for(int i  = 0; i < uList.size(); i++)
        {
            users.add(uList.get(i).getUserID());
        }
        
        //sort the users according to the alphabets then add to JList
        Collections.sort(users);
        
        for(int i  = 0; i < users.size(); i++)
        {            
            dlModel.add(i, users.get(i));
        }
        
        //set the default user selected
        jlUsers.setSelectedIndex(1);
        setTextFieldValue();
    }    
    
    /**
     * This method is to set text to UserID and Full Name
     */
    private void setTextFieldValue()
    {
        //get the selected userID to determine the full name
        //int selectedIndex = jlUsers.getSelectedIndex();
        if(jlUsers.getSelectedValue() == null)
        	return ;
    	
        String userID = jlUsers.getSelectedValue().toString();
        String fullName = "";
        
        for (int i = 0; i < uList.size(); i ++)
        {
            if (userID.equals(uList.get(i).getUserID().toString()))
            {
                fullName = uList.get(i).getFullname();
            }
        }
        
        //set the userID and full name text field
        jtxUserID.setText(userID);
        jtxFullName.setText(fullName);
    }
    
    private void deleteUser()
    {
    	// Validate User Selection
    	if(jlUsers.getSelectedValue() == null)
    	{
    		JOptionPane.showMessageDialog(null, "No User is selected for deletion", "Validation Error", JOptionPane.ERROR_MESSAGE);
    		return ;
    	}
    	
    	String optMsg = "Confirm to delete User '"+jtxUserID.getText()+":"+jtxFullName.getText()+"' ?";
		int option = JOptionPane.showConfirmDialog(null, optMsg, "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
		
		if(option == JOptionPane.OK_OPTION)
		{
			db.entity.UserAccount uItem = new db.entity.UserAccount();
			uItem.setFullname(jtxFullName.getText());
			uItem.setUserID(jtxUserID.getText());
			
			DatabaseManager db = new DatabaseManager();
			db.deleteUserAccount(uItem);
			Activity.log("Delete User  '"+jtxUserID.getText()+":"+jtxFullName.getText()+"'", "ADMIN", "");
			
			Authentication.updateUserList();
			uList.clear();
			initUsers();
		}	
		else
			return ;
    }
    
    private void createUser()
    {
    	// Validate blanks
    	if(jtxUserID.getText().equals("") || jtxUserID.getText() == null)
    	{
    		JOptionPane.showMessageDialog(null, "Please fill in both User ID and Full Name", "Validation Error", JOptionPane.ERROR_MESSAGE);
    		return ;
    	}
    	
    	if(jtxFullName.getText().equals("") || jtxFullName.getText() == null)
    	{
    		JOptionPane.showMessageDialog(null, "Please fill in both User ID and Full Name", "Validation Error", JOptionPane.ERROR_MESSAGE);
    		return ;
    	}
    	
    	String userID = jtxUserID.getText();
    	String existingFullName = "";
    	boolean existingID = false;
    	for(int i=0; i<uList.size(); i++)
    	{
    		String uItem = uList.get(i).getUserID();
    		if(uItem.equals(userID))
    		{
    			existingID = true;
    			existingFullName = uList.get(i).getFullname();
    			break;
    		}
    	}
    	
    	if(existingID)
    	{
    		String errMsg = "Confirm to overwrite '"+userID+":"+existingFullName+"' with '"+userID+":"+jtxFullName.getText()+"' ?";
    		int option = JOptionPane.showConfirmDialog(null, errMsg, "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
    		if(option == JOptionPane.OK_OPTION)
    		{
    			db.entity.UserAccount uItem = new db.entity.UserAccount();
    			uItem.setFullname(jtxFullName.getText());
    			uItem.setUserID(userID);
    			
    			DatabaseManager db = new DatabaseManager();
    			db.updateUserAccount(uItem);
    			Activity.log("Update User  '"+jtxUserID.getText()+":"+jtxFullName.getText()+"'", "ADMIN", "");
    			
    			Authentication.updateUserList();
    			uList.clear();
    			initUsers();
    		}
    		else
    			return ;
    	}
    	else
    	{
    		String errMsg = "Confirm to create new user '"+userID+":"+jtxFullName.getText()+"' ?";
    		int option = JOptionPane.showConfirmDialog(null, errMsg, "Confirm Create", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
    		if(option == JOptionPane.OK_OPTION)
    		{
    			db.entity.UserAccount uItem = new db.entity.UserAccount();
    			uItem.setFullname(jtxFullName.getText());
    			uItem.setUserID(userID);
    			
    			DatabaseManager db = new DatabaseManager();
    			db.updateUserAccount(uItem);
    			Activity.log("Create User  '"+jtxUserID.getText()+":"+jtxFullName.getText()+"'", "ADMIN", "");

    			Authentication.updateUserList();
    			uList.clear();    			
    			initUsers();
    		}
    		else
    			return ;
    	}
    }

    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManageUsersFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManageUsersFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManageUsersFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManageUsersFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ManageUsersFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
//    private javax.swing.JButton jbtSave;
    private javax.swing.JButton jbtCreate;
    private javax.swing.JButton jbtDelete;
//    private javax.swing.JButton jbtEdit;
    private javax.swing.JList jlUsers;
    private javax.swing.JTextField jtxFullName;
    private javax.swing.JTextField jtxUserID;
    // End of variables declaration
    private DatabaseManager dm;
    private DefaultListModel dlModel;
    private List <UserAccount> uList;
    
}
